package com.ad.pet.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ad.pet.App;
import com.ad.pet.Logger;
import com.ad.pet.MainActivity;
import com.ad.pet.MainActivityCompent;
import com.ad.pet.MainContract;
import com.ad.pet.MainPresenter;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.main.adapter.MainFloorAdapter;
import com.ad.pet.app.main.adapter.MainMenuAdapter;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.fragment.LoadingFragment;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.Money;
import com.ad.pet.models.remote.home.Cate;
import com.ad.pet.models.remote.home.Home;
import com.ad.pet.models.remote.home.NewUserBenfit;
import com.ad.pet.models.remote.home.Picture;
import com.ad.pet.models.remote.home.Product_list;
import com.ad.pet.models.remote.home.VpPacket;
import com.ad.pet.models.remote.home.floor.Floor;
import com.ad.pet.models.remote.login.Country;
import com.ad.pet.models.remote.main.DesingerMain;
import com.ad.pet.models.remote.main.DesingerStore;
import com.ad.pet.ui.RedBagCashDialog;
import com.ad.pet.ui.loopview.LoopView;
import com.ad.pet.ui.loopview.entity.LoopViewEntity;
import com.ad.pet.utils.LyxUtils;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.just.agentweb.LogUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * popular首页接口
 * Created by SEELE on 2018/12/20.
 */

public class HomeContentFragment extends LoadingFragment implements HomeContract.View ,MainContract.View{

    @BindView(R.id.linearlayout)
    LinearLayout mLinearLayout;
    @BindView(R.id.recycler_home)
    RecyclerView mRecyclerHome;


    @Inject
    HomePresenter mHomePresenter;//首页各个item接口


    @Inject
    RxDisposable mRxDisposable;
    private LoopView mLoopView;
    //    private List<Cate> mCates;
    private View mMenuView;
    private ImageView mIvCopous;
    private MainFloorAdapter mFloorAdapter;
    private View mViewAddress;
    private TextView tvAddress;
    private RecyclerView recyclerMenu;
    private MainMenuAdapter mainMenuAdapter;
    private TextView tvWidth;

    private String longTiue = "121.48";
    private String lenTiue = "31.22";
    private String locationProvider;
    private LocationManager locationManager;
    private Home home;
    private Country country;
    private ImageView ivMap;

    String commonUrl;
    private DesingerMain desingerMain;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
//声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public RedBagCashDialog kefuDialog;
    private ImageView ivPacket;
    @Inject
    MainPresenter mainPresenter;
    private Home userJump;

    @Override
    protected int contentLayout() {
        return R.layout.fragment_home_content;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initData() {
        kefuDialog = new RedBagCashDialog(getActivity(), R.style.custom_dialog_style);
        ivPacket = kefuDialog.findViewById(R.id.iv_packet);
        mHomePresenter.getPicList("3", longTiue, lenTiue);
        desingerMain=new DesingerMain();
        mainPresenter.getActivityCoupon();
    }


    @Override
    protected void initEvents() {

        ivPacket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userJump!=null){
                    if (1==(userJump.getHome_adv_list().get(0).getAdv_type())){
                        Navigation.goCommonWebView(getActivity(),"",userJump.getHome_adv_list().get(0).getAdv_url(),false,false,MainActivity.REQUEST_GO_MALL);
                    }
                }
                kefuDialog.dismiss();
            }
        });

        mainMenuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Cate cate = mainMenuAdapter.getItem(position);
                if (TextUtils.equals("1",cate.getNav_url())){
                    if (home != null) {
                        DesingerStore desingerStore = home.getShop_info();
                        Navigation.goDesignerStoreList(mFragment, desingerStore,longTiue,lenTiue);
                    }
                }else if (TextUtils.equals("2",cate.getNav_url())){
                    if (home!=null)
                    Navigation.goPetConcer(getActivity(),home.getShop_info(),longTiue,lenTiue);
                }else {

                    String action = "";
                    if (cate.getNav_url().contains("equity")){

                    }else {
                        if (!hasLogin()){
                            Navigation.goLogin(getActivity(),1,0);
                            return;
                        }
                     action =    "?token="+ SpUtil.getInstance().getString(Constant.ACCESS_TOKEN)+"&longitude="+longTiue+"&latitude="+lenTiue;
                    }
                    Navigation.goCommonWebView(getActivity(),cate.getNav_title(),cate.getNav_url()+action ,false);
                }
            }
        });

        mViewAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (home != null) {
                    DesingerStore desingerStore = home.getShop_info();
//                    if (country != null) {
//                        desingerStore.setCity_name(country.getCity_name());
//                        desingerStore.setProvince_id(country.getProvince_id());
//                        desingerStore.setCity_id(country.getCity_id());
//                        desingerStore.setLongtitu(longTiue);
//                        desingerStore.setLentitu(lenTiue);
//                    }else {
//                        desingerStore.setLongtitu(longTiue);
//                        desingerStore.setLentitu(lenTiue);
//                    }
                    ;

                    Navigation.goDesignerStoreList(mFragment, desingerStore,longTiue,lenTiue);
                }
            }
        });
        mRxDisposable.add(RxBus.getDefault().toObservable(DesingerMain.class).subscribe(new Action1<DesingerMain>() {
            @Override
            public void call(final DesingerMain desingerMain) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvWidth.setText("距离 " + desingerMain.getDistance() + "米");
                        double length = Double.valueOf(desingerMain.getDistance());
                        String juli = "";
                        if (length < 1000) {
                            juli = length + "m";
                        } else {
                            juli = LyxUtils.formatDouble2(length / 1000) + "km";
                        }
                        tvWidth.setText("距离 " +juli);
                        tvAddress.setText(desingerMain.getShop_name());
                        home.getShop_info().setCity_id(desingerMain.getCity_id());
                        home.getShop_info().setCity_name(desingerMain.getCity_name());
                        home.getShop_info().setProvince_id(desingerMain.getPrivoince_id());
                        home.getShop_info().setLatitude_longitude(desingerMain.getLatitude_longitude());
                        home.getShop_info().setShop_id(desingerMain.getShop_id());
                    }
                });

            }
        }));

        mLoopView.setOnItemClickListener(new LoopView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!TextUtils.isEmpty(home.getBanner_list().get(position).getUrl())) {
                    Navigation.goCommonWebView(getActivity(), "", home.getBanner_list().get(position).getUrl(), false, false, MainActivity.REQUEST_GO_MALL);
                }
            }
        });

        mIvCopous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(home.getMember_adv_list().get(0).getAdv_url())) {
                    Navigation.goCommonWebView(getActivity(), "", home.getMember_adv_list().get(0).getAdv_url()+"?token="+SpUtil.getInstance().getString(Constant.ACCESS_TOKEN), false, false, MainActivity.REQUEST_GO_MALL);
                }
            }
        });

        mFloorAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                commonUrl = mFloorAdapter.getData().get(position).getAdv_url()+"?token="+SpUtil.getInstance().getString(Constant.ACCESS_TOKEN);
                if (TextUtils.equals(getString(R.string.ip_default)+"/index.php/wap/index",mFloorAdapter.getData().get(position).getAdv_url())){
                    if (hasLogin()){
                        Navigation.goCommonWebView(getActivity(), "商城",commonUrl , false, true, MainActivity.REQUEST_GO_MALL);
                    }else {
                        Navigation.goLogin(getActivity(),1,1);
                    }

                    return;
                }
                if (!TextUtils.isEmpty(mFloorAdapter.getData().get(position).getAdv_url())) {
                    Navigation.goCommonWebView(getActivity(), "",commonUrl , false, false, MainActivity.REQUEST_GO_MALL);
                }
            }
        });

        ivMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                PackageManager packageManager = getActivity().getPackageManager();
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT){
                    ToastUtil.getToastUtil().showShort("您的手机系统暂不支持该服务！");
                    return;
                }
                LogUtils.e("--->",home.getShop_info().getLatitude()+"|"+home.getShop_info().getLongitude() );
                Intent intent = null;
                    if (isAvailable("com.autonavi.minimap")) {
//                    intent = packageManager.getLaunchIntentForPackage("com.autonavi.minimap");
                        double mydout[]=bdToGaoDe(Double.valueOf(home.getShop_info().getLongitude()),Double.valueOf(home.getShop_info().getLatitude()));

                    Uri uri = Uri.parse("amapuri://route/plan/?dlat=" + mydout[0]+ "&dlon=" + mydout[1] + "&dname=" + home.getShop_info().getShop_name() + "&dev=0&t=0");
//                    Activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    intent = new Intent(Intent.ACTION_VIEW, uri);

                } else if (isAvailable("com.baidu.BaiduMap")) {
//                    intent = packageManager.getLaunchIntentForPackage("com.baidu.BaiduMap");
                    Uri uri = Uri.parse("baidumap://map/direction?destination=latlng:" + home.getShop_info().getLatitude() + "," + home.getShop_info().getLongitude() + "|name:" + home.getShop_info().getShop_name() + "&mode=driving");
                    intent = new Intent(Intent.ACTION_VIEW, uri);
                } else if (isAvailable("com.tencent.map")) {
//                    intent = packageManager.getLaunchIntentForPackage("com.tencent.map");
                    Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=" + home.getShop_info().getShop_name() + "&tocoord=" + home.getShop_info().getLatitude() + "," + home.getShop_info().getLongitude() + "&policy=2&referer=myapp");
                    intent = new Intent(Intent.ACTION_VIEW, uri);
                } else {
                    ToastUtil.getToastUtil().showShort("手机暂无地图应用");
                    return;
                }

                startActivity(intent);
            }
        });
    }

    //4465.32
    @Override
    protected void initViews() {
//初始化定位
        mLocationClient = new AMapLocationClient(App.getApp());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);

//获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);


        if(null != mLocationOption){
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
//        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
//        List<String> providers = locationManager.getProviders(true);
//
//        if (providers.contains(LocationManager.GPS_PROVIDER)) {
//            //如果是GPS
//            locationProvider = LocationManager.GPS_PROVIDER;
//        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//            //如果是Network
//
//            locationProvider = LocationManager.NETWORK_PROVIDER;
//        }
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        } else {
//            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
//            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, locationListener);
//
//            showLocation();


        }

        mHomePresenter.onCreate(this);
        mainPresenter.onCreate(this);

        mFloorAdapter = new MainFloorAdapter(null);
        mRecyclerHome.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerHome.setAdapter(mFloorAdapter);

        //banner部分
        View bannerView = LayoutInflater.from(getActivity()).inflate(R.layout.item_loopview_layout, null);
        mLoopView = bannerView.findViewById(R.id.loopView);


        //首页menu部分
        mMenuView = LayoutInflater.from(getActivity()).inflate(R.layout.item_recyclerview, null);
        recyclerMenu = mMenuView.findViewById(R.id.recycerview);
//        mCates = new ArrayList<>();
        initMenu();


        //首单全返活动规则入口
        View CopousView = LayoutInflater.from(getActivity()).inflate(R.layout.item_new_copous, null);
        mIvCopous = CopousView.findViewById(R.id.iv_activity);


        mViewAddress = LayoutInflater.from(getActivity()).inflate(R.layout.item_new_user_layout, null);
        tvAddress = mViewAddress.findViewById(R.id.tv_address);
        tvWidth = mViewAddress.findViewById(R.id.tv_width);
        ivMap = mViewAddress.findViewById(R.id.iv_ditu);
        mViewAddress.findViewById(R.id.tv_width);


        mFloorAdapter.addHeaderView(bannerView);
//        mFloorAdapter.addHeaderView(mViewAddress);
        mFloorAdapter.addHeaderView(mMenuView);
        mFloorAdapter.addHeaderView(CopousView);

        mFloorAdapter.notifyDataSetChanged();


    }

    private void showLocation() {


        @SuppressLint("MissingPermission") final Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            longTiue = Math.abs(location.getLongitude()) + "";
            lenTiue = Math.abs(location.getLatitude()) + "";
            App.longTitu=longTiue;
            App.latitude=lenTiue;
            Logger.e("tag--->",longTiue+":"+lenTiue);
            mHomePresenter.getPicList("3", longTiue, lenTiue);
        }
    }

    @Override
    public void onResume() {
        super.onResume();


    }

    @Override
    public void initInjector() {
        getComponent(MainActivityCompent.class).inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return mHomePresenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {


    }


    @Override
    public void getPicListSuccess(final Home commList) {

        home = commList;
        initBanner(commList.getBanner_list());
        mainMenuAdapter.setNewData(commList.getNavigation_list());
        double length = Double.valueOf(commList.getShop_info().getDistance());
        String juli = "";
        if (length < 1000) {
            juli = length + "m";
        } else {
            juli = LyxUtils.formatDouble2(length / 1000) + "km";
        }
        commList.getShop_info().setLatitude(getLongAndLatute(commList.getShop_info().getLatitude_longitude())[1]);
        commList.getShop_info().setLongitude(getLongAndLatute(commList.getShop_info().getLatitude_longitude())[0]);
        tvWidth.setText("距离 " + juli);
        tvAddress.setText(commList.getShop_info().getShop_name());
        GlideUtil.load(mFragment, commList.getMember_adv_list().get(0).getAdv_image(), mIvCopous);


        List<Floor> floors = new ArrayList<>();
        commList.getShop_adv_list().get(0).setType("商城");
        floors.addAll(commList.getShop_adv_list());
        commList.getService_adv_list().get(0).setType("上门服务");
        floors.addAll(commList.getService_adv_list());

        mFloorAdapter.setNewData(floors);

        mFloorAdapter.notifyDataSetChanged();
        mStatusLayoutManager.showContent();


    }

    private void initBanner(List<Picture> commList) {
        List<LoopViewEntity> mListLoop = new ArrayList<>();
        for (int i = 0; i < commList.size(); i++) {
            LoopViewEntity entity = new LoopViewEntity();
            entity.setImageUrl(commList.get(i).getImg());
            entity.setDescript("");
            mListLoop.add(entity);
        }
        mLoopView.setLoopData(mListLoop);
    }

    @Override
    public void getFeatureDataColumnSuccess(Cate cates) {


//        mPopCate = cates;
//        GlideUtil.loadNoDefault(getActivity(), cates.getImg(), mIvRdbg);


    }


    @Override
    public void getVpPacketsSuccess(List<VpPacket> resultBean) {

//        GlideUtil.loadNoDefault(getActivity(),mVpPackets.get(0).getImage(), mIvCopous);

    }

    @Override
    public void getNewUserBenfits(NewUserBenfit benfit) {

    }

    @Override
    public void getNewUserGoodsSuccess(Product_list product_list) {

    }


    public static HomeContentFragment newInstance() {
        Bundle args = new Bundle();
        HomeContentFragment fragment = new HomeContentFragment();
        fragment.setArguments(args);
        return fragment;
    }


    private void initMenu() {

        mainMenuAdapter = new MainMenuAdapter(null);
        recyclerMenu.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        recyclerMenu.setAdapter(mainMenuAdapter);

    }
//
//    private List<Address> getAddress(Location location) {
//        List<Address> result = null;
//        try {
//            if (location != null) {
//                Geocoder gc = new Geocoder(getActivity(), Locale.getDefault());
//                result = gc.getFromLocation(location.getLatitude(),
//                        location.getLongitude(), 1);
//                cityLocation = result.get(0).getSubAdminArea();
////                for (int i = 0; i < result.size(); i++) {
////                    Logger.e("addresss------>"+result.get(i));
////                }
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return result;
//    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }


    }


    public boolean isAvailable(String mapPackageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = getActivity().getPackageManager().getPackageInfo(mapPackageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo == null ? false : true;
    }


    private String[] getLongAndLatute(String l) {
        return l.split(",");
    }



    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            longTiue = gaoDeToBaidu(aMapLocation.getLongitude(),aMapLocation.getLatitude())[0]+"";
            lenTiue = gaoDeToBaidu(aMapLocation.getLongitude(),aMapLocation.getLatitude())[1]+"";

            App.longTitu=longTiue;
            App.latitude=lenTiue;
            Logger.e("tag--->",longTiue+":"+lenTiue);

        }
    };

    private double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }
    private double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }

    @Override
    public void getActivityCouponSuccess(Home user) {
        userJump = user;
        kefuDialog.show();
        GlideUtil.load(getActivity(), user.getHome_adv_list().get(0).getAdv_image(), ivPacket);
    }

    @Override
    public void getMoneySuccess(List<Money> money) {

    }

    @Override
    public void checkTokenStatus(int type) {
        if (type!=1){
            SpUtil.getInstance().putString(Constant.ACCESS_TOKEN,"");
            Navigation.goLogin(getActivity(),1,1);
        }else {
            Navigation.goCommonWebView(getActivity(), "",commonUrl , false, false, MainActivity.REQUEST_GO_MALL);
        }
    }
}
